import React, { useEffect, useRef, useState } from 'react';
import './amap.css';

// 高德地图全局对象类型定义
declare global {
  interface Window {
    AMap: any; // 高德地图主对象
    AMapLoader: any; // 地图加载器
  }
}

interface AmapMapProps {
  /** 高德地图开发者Key */
  mapKey: string;
  /** 地图初始中心点 [经度, 纬度] */
  center?: [number, number];
  /** 地图初始缩放级别 */
  zoom?: number;
  /** 地图容器高度 */
  height?: string;
}

const Amap: React.FC<AmapMapProps> = ({
  mapKey,
  center = [116.39748, 39.90882], // 默认北京坐标
  zoom = 7,
  height = '600px'
}) => {
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const [mapInstance, setMapInstance] = useState<any>(null); // 地图实例
  const [isLoading, setIsLoading] = useState(true); // 加载状态

  // 初始化地图
  useEffect(() => {
    // 加载高德地图SDK
    const loadAmapScript = async () => {
      try {
        // 检查是否已加载地图SDK
        if (window.AMapLoader) {
          initMap();
          return;
        }

        // 动态加载高德地图SDK
        const script = document.createElement('script');
        script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.Scale,AMap.ToolBar`;
        script.async = true;
        script.onload = initMap;
        script.onerror = () => {
          setIsLoading(false);
          console.error('高德地图SDK加载失败');
        };
        document.body.appendChild(script);

        return () => {
          document.body.removeChild(script);
        };
      } catch (error) {
        setIsLoading(false);
        console.error('地图初始化异常:', error);
      }
    };

    // 初始化地图实例
    const initMap = async () => {
      try {
        if (!mapContainerRef.current) return;

        // 等待地图加载器初始化地图
        const AMap = window.AMap;
        const map = new AMap.Map(mapContainerRef.current, {
          center,
          zoom,
          resizeEnable: true, // 允许地图大小自适应
          zoomEnable: true, // 允许缩放
          dragEnable: true, // 允许拖拽
        });

        const satelliteLayer = new window.AMap.TileLayer.Satellite({
          zooms: [1, 18], // 卫星图层支持的缩放级别范围
          opacity: 1 // 图层透明度
        });
        map.add(satelliteLayer); // 将卫星图层添加到地图

        setMapInstance(map);
        setIsLoading(false);
      } catch (error) {
        setIsLoading(false);
        console.error('地图初始化失败:', error);
      }
    };

    loadAmapScript();

    // 组件卸载时销毁地图
    return () => {
      if (mapInstance) {
        mapInstance.destroy();
        setMapInstance(null);
      }
    };
  }, [mapKey, center, zoom]);

  return (
    <div className="amap-container" style={{ height }}>
      {isLoading && (
        <div className="amap-loading">
          <div className="spinner"></div>
          <p>地图加载中...</p>
        </div>
      )}
      <div 
        ref={mapContainerRef} 
        className="amap-map"
        style={{ height: '100%', width: '100%' }}
      ></div>
    </div>
  );
};

export default Amap;
    